import { useEffect, useState } from "react";

const HighScores = () => {

  const [scores, setScores] = useState([]);

  const loadData = () => {
    fetch(`${process.env.PUBLIC_URL}/high-scores`)
      .then(response => response.json())
      .then(data => setScores(data));
  };

  useEffect(() => {
    const intervalId = setInterval(() => {
      loadData();
    }, 5000);
    loadData();

    return () => clearInterval(intervalId);
  }, []);

  const displayScore = (score) => {
    let secs = parseInt(score);
    let mins = Math.floor(secs / 60);
    secs = secs % 60;
    
    const i = score.indexOf('.') + 1
    let ms = score.substring(i, i + 2);

    return `${mins}m ${secs}s ${ms}ms`;
  };

  return (
    <div className="highscores">
      <h1>Highscores</h1>
      <table className="tbl-highscores">
        <thead>
          <tr>
            <th>Player</th>
            <th>Score</th>
            <th>Seed</th>
          </tr>
        </thead>
        <tbody>
          {scores.map((x, idx) => 
          <tr key={idx}>
            <td>{x.name}</td>
            <td>{displayScore(x.score)}</td>
            <td className="seed">{x.seed}</td>
          </tr>)}
        </tbody>
      </table>
    </div>
  );
}

export default HighScores;
